package com.prep;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleAdapter;

public class ShowDiaryActivity extends ListActivity {
	private String diary;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		OnBootReceiver.setupAlarms(this);

		setContentView(R.layout.diary);
		diary = PreferenceManager.getDefaultSharedPreferences(this).getString(
				"diary",
				DateFormat.getDateFormat(this).format(new Date())
						+ " - Ingen dagbogs noter skrevet endnu ;");

		String[] diaryEntries = diary.split(";");

		String[] from = new String[] { "text1", "text2" };

		int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

		List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

		for (String diaryEntry : diaryEntries) {
			String[] dateEntry = diaryEntry.split("-");
			if (dateEntry.length == 2) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("text1", dateEntry[0]);
				map.put("text2", dateEntry[1]);

				fillMaps.add(map);
			}
		}

		SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
				android.R.layout.simple_list_item_2, from, to);

		setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("Export");
		menu.add("New diary entry");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Export")) {
			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("plain/text");
			emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
					new String[] { "allan.stisen@gmail.com",
							"b.jungberg@gmail.com" });
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
					"PREP KURSUS DAGBOG");
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, diary
					.replace(";", "\n\n").replace("-", "\n"));
			startActivity(emailIntent);
		} else {
			startActivity(new Intent(this, EnterDiaryEntry.class));
		}
		return true;
	}
}
